require( '$d/css/common.less' );
require( './style.less' );
define( [
  'require',
  'jquery',
  'header',
  'constants',
  'message',
  'behavior',
  'login',
  'combiner',
  'searchMaterial'
], function( require, $ ) {
  var constants = require( 'constants' ),
    message = require( 'message' ),
    behavior = require( 'behavior' ),
    login = require( 'login' ),
    searchMaterial = require( 'searchMaterial' );

  searchMaterial.onSearch = function( keyword ) {
    window.location.href = '/topic/search?keyword=' + keyword;
  }
  var myAjax = function( opt ) {
      $.ajax( {
        type: 'post',
        url: opt[ 'url' ],
        data: opt[ 'data' ],
        success: function( data ) {
          if ( $.isFunction( opt[ 'callBack' ] ) ) {
            opt[ 'callBack' ]( data );
          }
        },
        error: function( XMLHttpRequest, textStatus, errorThrown ) {
          console.log( textStatus );
          console.log( XMLHttpRequest.status );
          console.log( XMLHttpRequest.readyState );
        }
      } );
    },
    params = {
      url: require( 'api' ).TOPIC.GET_TOPIC,
      data: {
        p: 1,
        l: 15,
        s: 'top.baidu.com',
        cn: '实时热点',
      },
      callBack: judge,
      pg: false,
    };
  var content = $( '.topic' );
  content.find( ".nav_box" ).lavalamp( {
    fx: "backout",
    speed: 700,
    click: function( event, menuItem ) {
      var $t = $( menuItem );
      content.find( '.sidemenu > a' ).addClass( 'hide' ).removeClass( 'green' );
      content.find( '.sidemenu' ).removeClass( 'baidu' ).removeClass( 'sina' ).removeClass( 'sogou' );
      if ( $t.index() == 0 ) {
        content.find( '.sidemenu' ).addClass( 'baidu' );
        content.find( '.sidemenu > a' ).not( ':nth-child(7),:nth-child(8),:nth-child(9)' ).removeClass( 'hide' );
        content.find( '.sidemenu > a' ).eq( 0 ).addClass( 'green' );
      } else if ( $t.index() == 1 ) {
        content.find( '.sidemenu' ).addClass( 'sina' );
        content.find( '.sidemenu > a:nth-child(7),.sidemenu > a:nth-child(8)' ).removeClass( 'hide' );
        content.find( '.sidemenu > a' ).eq( 6 ).addClass( 'green' );
      } else if ( $t.index() == 2 ) {
        content.find( '.sidemenu' ).addClass( 'sogou' );
        content.find( '.sidemenu > a:nth-child(1),.sidemenu > a:nth-child(3)' ).removeClass( 'hide' );
        content.find( '.sidemenu > a' ).eq( 0 ).addClass( 'green' );
      }
      /* else if ($t.index() == 3) {
                      content.find('.sidemenu > a').not(':nth-child(2),:nth-child(5)').addClass('hide');
                      content.find('.sidemenu > a').eq(1).addClass('green');
                  }*/
      params.data.cn = content.find( '.sidemenu > a.green' ).text();
      params.data.s = $t.data( 's' );
      params.data.p = 1;
      params.pg = true;
      myAjax( params );
    }
  } );

  content.find( '.sidemenu > a' ).click( function() {
    if ( $( this ).hasClass( 'green' ) ) {
      return;
    }
    $( this ).addClass( 'green' ).siblings().removeClass( 'green' );
    params.data.cn = $( this ).text();
    params.pg = true;
    params.data.p = 1;
    myAjax( params );
  } )

  function judge( data ) {
    message.show( '正在加载...' );
    var json = typeof data === 'string' ? $.parseJSON( data ).data : data.data,
      html = '';
    var s = ( json.total_pages || 0 );

    if ( params.pg ) {
      if ( s > 1 ) {
        content.find( '.topic_paging' ).removeClass( 'hide' );
      } else {
        content.find( '.topic_paging' ).addClass( 'hide' );
      }
      content.find( '.topic_paging' ).attr( 'data-total', s ).data( 'total', s );
      tpc_pag();
    }

    if ( json.topics.length > 0 ) {
      for ( var i in json.topics ) {
        var list_data = json.topics[ i ];
        ( !!list_data.summary && list_data.summary != '' && list_data.summary != undefined ) ? ( html += '<li>' ) : ( html += '<li class="details">' );
        if ( list_data.source == 'top.baidu.com' ) {
          html += '<div class="details_summary details_fluid">';
        } else {
          if ( list_data.cover_img_url ) {
            if ( list_data.source == 'd.weibo.com' || ( list_data.source != 'd.weibo.com' && i < 3 ) ) {
              html += '<a href="/_topic/details/cd/' + list_data.cd + '/category/' + $( '.sidemenu > .green' ).text() + '/s/' + list_data.source + '" target="_blank"><img src="' + list_data.cover_img_url + '" class="cover" onerror="this.src=\"' + constants.resPath + '/images/wuyulantu.png\";"></a><div class="details_summary">';
            } else {
              html += '<div class="details_summary details_fluid">';
            }
          } else {
            html += '<div class="details_summary details_fluid">';
          }
        }
        html += '<p class="details_title"><span class="iconfont icon-huati ' + ( i < 3 ? 'r_icon' + ( list_data.rank ) : '' ) + '"></span><span class="ranking">' + list_data.rank + '</span><a href="/_topic/details/cd/' + list_data.cd + '/category/' + $( '.sidemenu > .green' ).text() + '/s/' + list_data.source + '" target="_blank">' + list_data.title + ' </a>';
        if ( list_data.new_flags == 1 ) {
          html += '<img src="' + constants.resPath + '/images/new1.png">';
        }
        html += '</p>';
        if ( list_data.summary && list_data.summary != '' && list_data.summary != undefined ) {
          html += '<a href="javascript:void(0)" class="details_epitome">' + list_data.summary + '</a>';
        }
        html += '</div><span class="s1">' + ( ( list_data.read_value == 0 ) ? ( list_data.index_value ) : ( list_data.read_value ) ) + ' ';
        if ( list_data.trend_flags == 'rise' ) {
          html += '<span class="glyphicon glyphicon-arrow-up green"></span>'
        } else if ( list_data.trend_flags == 'fall' ) {
          html += '<span class="glyphicon glyphicon-arrow-down red"></span>'
        } else if ( list_data.trend_flags == 'fair' ) {
          html += '<span class="glyphicon glyphicon-minus"></span>'
        };
        html += '</span><span class="s2"><a href="/search/articles/search_key/' + list_data.title + '" target="_blank">相关文章</a></span><span class="pull-right s3" data-cd="' + list_data.cd + '" data-title="' + list_data.title + '" data-source="' + list_data.source + '"><span class="iconfont icon-icon- add_compare' + ( ( list_data.is_comb != 0 ) ? ' green' : '' ) + '"></span></span></li>';
      }
    } else {
      html = '<li class="no_content"><span class="glyphicon glyphicon-flash"></span>暂无内容</li>';
    }
    content.find( '.list' ).empty().append( html );
    message.hide();
  }

  /**
   * ========== * 话题列表分页* ==========
   */

  content.on( 'click', '.fornoprefetch', tpc_pag );
  content.on( 'click', '.paging_right', tpc_pag );
  content.on( 'click', '.prev_prepage', tpc_pag );
  content.on( 'click', '.new_firstpage', tpc_pag );

  function tpc_pag() {
    var num = $( this ).data( 'direction' ) || 0,
      total_pages = content.find( '.topic_paging' ).data( 'total' ),
      page = params.data.p;
    if ( num == 0 ) {
      page = 1
    } else if ( num == 1 ) {
      page--
    } else {
      if ( page == total_pages ) {
        message.showWarning( '已经最后一页！', 2000 );
        return;
      }
      page++
    }
    if ( page == 1 ) {
      $( '.paging_right' ).attr( 'class', 'fornoprefetch' );
      $( '.topic_paging > div' ).not( '.fornoprefetch' ).addClass( 'hide' );
      if ( params.pg ) {
        params.pg = false;
        return;
      }
    } else if ( page == 2 ) {
      $( '.fornoprefetch' ).attr( 'class', 'paging_right' );
      $( '.topic_paging > div' ).removeClass( 'hide' )
      $( '.new_firstpage' ).addClass( 'hide' )
    } else if ( page == 3 ) {
      $( '.new_firstpage' ).removeClass( 'hide' )
    }

    $( '.new_nowpage > i' ).text( page );

    if ( params.pg ) {
      params.pg = false;
      return;
    } else {
      params.data.p = page;
      window.scrollTo( 0, 0 );
      myAjax( params );
    }
  }

  content.find( '.topic_time' ).click( function() {
    params.data.order = $( this ).data( 'order' );
    params.pg = true;
    params.data.p = 1;
    $( this ).addClass( 'green' );
    content.find( '.topic_heat' ).removeClass( 'green' );
    myAjax( params );
  } )

  content.find( '.topic_heat' ).click( function() {
    params.data.order = $( this ).data( 'order' );
    params.pg = true;
    params.data.p = 1;
    $( this ).addClass( 'green' );
    content.find( '.topic_time' ).removeClass( 'green' );
    myAjax( params );
  } );
  searchMaterial.addClassByIndex( 0 );

  /**
   *=================
   * 对比列表
   *=================
   */
  var aside_wrap = $( '.content_wrapper' );
  var aside_num = '';
  var aside = {
    url: '/_topic/get_comb_compare',
    callBack: parallel_list
  };

  var srce = {
    text: {
      'd.weibo.com': '新浪微博',
      'top.baidu.com': '百度风云榜',
      'top.sogou.com': '搜狗热搜榜',
      'top.so.com': '360热搜榜',
    },
    icon: {
      'd.weibo.com': 'icon-iconfontweibo',
      'top.baidu.com': 'icon-baidu',
      'top.sogou.com': 'icon-sougou red',
      'top.so.com': 'icon-icon-test',
    }
  };
  myAjax( aside );

  function parallel_list( data ) {
    var data = typeof data === 'string' ? $.parseJSON( data ) : data;
    var htm = '';
    aside_num = ( data.data.total == 0 ) ? '' : ( data.data.total * 1 );
    if ( data.data.total == 0 ) {
      htm = '<p><span class="glyphicon glyphicon-flash"></span>&nbsp;暂无内容</p>';
    } else {
      htm += '<div class="delete_btn"><span class="remove_all" data-num="all">全部移出</span></div>'
      for ( i in data.data.topic_comb ) {
        var $data = data.data.topic_comb[ i ];
        htm += '<div class="contrast_info" data-cd="' + $data.cd + '"><p>' + $data.title.toString().replace( /(#)/g, "" ) + '</p><button type="button" class="icon_mark"><span class="iconfont ' + srce.icon[ $data.source ] + '"></span>' + srce.text[ $data.source ] + '</button> <button type="button" class="remove_btn pull-right">移出对比</button> </div>';
      }
    }
    aside_wrap.find( '.contrast_list' ).empty().append( htm );
    $( '.contrast_number' ).text( aside_num );
  };

  /**
   * ========== * 加入对比* ==========
   */
  content.on( 'click', '.add_compare', function( e ) {
    e.stopPropagation();
    if ( $( this ).hasClass( 'green' ) ) {
      message.showWarning( '已加入对比列表！', message.showTime );
      return;
    }
    behavior.addRecord( {
      category: behavior.topicComparison,
      action: behavior.action.click
    } );
    var offset = $( this ).offset();
    var endOffset = $( ".merger" ).offset();
    $( "<span class='iconfont icon-icon- green add_contrast'></span>" ).css( {
      top: offset.top,
      left: offset.left
    } ).appendTo( 'body' ).animate( {
      top: endOffset.top + 4,
      left: endOffset.left,
      fontSize: 20
    }, 800, function() {
      $( '.add_contrast' ).remove();
    } );
    var $this = $( this );
    var $data;
    $data = {
      cd: $this.parent().data( 'cd' ),
      title: $this.parent().data( 'title' ),
      source: $this.parent().data( 'source' )
    }
    $.ajax( {
      type: 'post',
      url: '/_topic/add_topic',
      data: {
        cd: $data.cd,
        title: $data.title,
        source: $data.source,
        category: $( '.sidemenu > .green' ).text(),
      },
      success: function( data ) {
        var json = typeof data === 'string' ? $.parseJSON( data ) : data;
        if ( json.ret == 0 ) {
          $this.addClass( 'green' );
          parallel_list( json );
        } else {
          message.showWarning( json.msg, message.showTime );
        }
      }
    } );
  } );

  aside_wrap.find( '.contrast_btn' ).click( parallel_btn );
  aside_wrap.on( 'click', '.remove_btn', aside_remove );
  aside_wrap.on( 'click', '.remove_all', aside_remove );

  function parallel_btn() {
    if ( aside_num < 2 || aside_num == undefined ) {
      message.showWarning( '请选择对比的话题,最少选择两个', message.showTime );
      return false;
    } else {
      window.open( '_topic/contrast', 'contrast' );
    }
  };

  function aside_remove() {
    var t = $( this );
    var _cd = '';
    if ( t.data( 'num' ) == 'all' ) {
      aside_wrap.find( '.contrast_info' ).each( function() {
        if ( _cd.length > 1 ) {
          _cd += ',';
        }
        _cd += $( this ).data( 'cd' );
      } )
    } else {
      _cd = t.parent().data( 'cd' );
    }
    $.ajax( {
      type: 'post',
      url: '/_topic/del_topic',
      data: {
        cd: _cd
      },
      success: function( data ) {
        var d = typeof data === 'string' ? $.parseJSON( data ) : data;
        if ( d.ret == 0 ) {
          if ( t.data( 'num' ) == 'all' ) {
            aside_wrap.find( '.contrast_list' ).children().remove();
            content.find( '.add_compare' ).removeClass( 'green' );
            aside_num = 0;
          } else {
            t.parent().remove();
            content.find( '[data-cd=' + _cd + ']' ).find( '.add_compare' ).removeClass( 'green' );
            aside_num -= 1;
          }
          var j = ( aside_num == 0 ) ? '' : aside_num;
          $( '.contrast_number' ).text( j );
          if ( aside_num == 0 ) {
            aside_wrap.find( '.contrast_list' ).empty().append( '<p><span class="glyphicon glyphicon-flash"></span>&nbsp;暂无内容</p>' );
          }
        }
      }
    } )
  };

  login.addLoginCallback( function() {
    myAjax( aside );
    myAjax( params );
  } );
} )